<template>
    <div class="login-body">
        <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="login-form">
            <h2 class="login-title">学校管理系统</h2>
            <el-form-item prop="username">
                <el-input v-model="ruleForm.username" clearable style="height: 45px;" placeholder="请输入用户名！">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <Avatar />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input v-model="ruleForm.password" type="password" clearable show-password style="height: 45px;"
                    placeholder="请输入密码！">
                    <template #prefix>
                        <el-icon class="el-input__icon">
                            <Lock />
                        </el-icon>
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
                <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Lock, Avatar } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import get_token from '@/utils/login';

const router = useRouter()
const ruleFormRef = ref<FormInstance>()

const validatePass = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('密码不能为空！'))
    } else {
        callback()
    }
}
const validateUsername = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('用户名不能为空！'))
    } else {
        callback()
    }
}

const ruleForm = reactive({
    password: 'hrj',
    username: 'hrj'
})

const rules = reactive<FormRules<typeof ruleForm>>({
    password: [{ validator: validatePass, trigger: 'blur' }],
    username: [{ validator: validateUsername, trigger: 'blur' }],
})

const getuser = async (ruleForm: any) => {
    await get_token(ruleForm)
}
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate(async (valid) => {
        if (valid) {
            await getuser(ruleForm)
            const token = sessionStorage.getItem("token") || ""
            if (token) {
                router.push('/layout')
            }
        } else {
            ElMessage.error('你没有输入用户名或密码！')
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}


</script>
<style scoped>
@import url('../../assets/login/login.css');
</style>